package com.cn.clp.weChat;

import net.sf.json.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class AccessToken {
    private  String grant_type = "client_credential";
    private  String appid = "wx8fd3b10de66352bc";
    private  String secret = "2cb1e583d47281d0c6cf121a2f3486aa";

    public  String getAccessToken() throws Exception{
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?" +
               "grant_type=client_credential&appid=wx8fd3b10de66352bc&secret=2cb1e583d47281d0c6cf121a2f3486aa";
       // String accessTokenUrl  = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx8fd3b10de66352bc&secret=2cb1e583d47281d0c6cf121a2f3486aa&code=001NHMEU0eTBdU1yReHU0tGSEU0NHMEM&grant_type=authorization_code";
        URL url = new URL(accessTokenUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        //获取返回的字符
        InputStream inputStream = connection.getInputStream();
        int size =inputStream.available();
        byte[] bs =new byte[size];
        inputStream.read(bs);
        String message = new String(bs,"UTF-8");
        System.out.println(message);
        JSONObject.fromObject(message);
        Map map = (Map)JSONObject.fromObject(message);
        map.get("access_token");
        System.out.println(map.get("access_token"));

        return map.get("access_token").toString();

    }

    public static void main(String[] args) throws Exception {
        String access_token = new AccessToken().getAccessToken();
        String getJsApiTiketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
        URL url1 = new URL(getJsApiTiketUrl);
        HttpURLConnection connection = (HttpURLConnection) url1.openConnection();

        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        //获取返回的字符
        InputStream inputStream = connection.getInputStream();
        int size =inputStream.available();
        byte[] bs =new byte[size];
        inputStream.read(bs);
        String message1 = new String(bs,"UTF-8");

        JSONObject.fromObject(message1);
        Map map = (Map)JSONObject.fromObject(message1);
        map.get("ticket");
        System.out.println(map.get("ticket").toString());

    }
}
